<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="../../../component/pear/css/pear.css"/>
    <link rel="stylesheet" href="../../../admin/css/reset.css"/>
</head>

<body>
<form class="layui-form" action="">
    <div class="mainBox">
        <div class="main-container">
            <div class="layui-form-item">
                <label class="layui-form-label">部门名称</label>
                <div class="layui-input-block">
                    <div id="pid" name="pid"></div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">岗位编号</label>
                <div class="layui-input-block">
                    <input type="text" id="position_code" maxlength="16" name="position_code" lay-verify="required" placeholder="编号" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">岗位名称</label>
                <div class="layui-input-block">
                    <input type="text" id="position_name" maxlength="16" name="position_name" lay-verify="required" placeholder="名称" class="layui-input">
                </div>
            </div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="layui-btn layui-btn-normal layui-btn-sm" lay-submit="" lay-filter="form-save">
                <i class="layui-icon layui-icon-ok"></i>
                提交
            </button>
            <button type="reset" class="layui-btn layui-btn-primary layui-btn-sm">
                <i class="layui-icon layui-icon-refresh"></i>
                重置
            </button>
        </div>
    </div>
</form>


<script src="../../../component/layui/layui.js"></script>
<script src="../../../component/pear/pear.js"></script>
<script src="../../../lms/base64.js"></script>
<script src="../../../lms/common.js"></script>
<script src="../../../lms/config.js"></script>
<script>

    const PRIMARY_KEY = "id";

    const DETAIL_API = lms_config.api_url + "/api/setting/position/get";
    const SELECT_API = lms_config.api_url + "/api/setting/position/select";
    const INSERT_API = lms_config.api_url + "/api/setting/position/insert";
    const UPDATE_API = lms_config.api_url + "/api/setting/position/update";
    const DELETE_API = lms_config.api_url + "/api/setting/position/delete";
    const SELECT_DEPT_API = lms_config.api_url + "/api/setting/dept/select";

    if (!checkLogin()) {
        location.href = lms_config.base_path + "/login.html";
    }


    layui.use(['form', 'jquery', 'laytpl', 'http', 'encrypt', 'xmSelect'], function () {
        let form = layui.form;
        let encrypt = layui.encrypt;
        let $ = layui.jquery;
        const laytpl = layui.laytpl;
        const http = layui.http;
        let method = 'POST';
        if (getQueryString('operation') === 'edit') {
            method = 'PUT';
        }

        /**
         * 获取部门
         */
        function getSuperiorDept() {
            $.ajax({
                url: SELECT_DEPT_API,
                dataType: "json",
                headers: {Authorization: getUserInfo()["token"]},
                success: function (res) {
                    let list = convertToTreeData(res.data, 'id', 'pid', 'department_name');
                    let value = layui.$("#pid").attr("value");
                    let initValue = value ? value.split(",") : [];
                    layui.xmSelect.render({
                        el: "#pid",
                        name: "pid",
                        initValue: initValue,
                        tips: "无",
                        toolbar: {show: true, list: ["CLEAR"]},
                        data: list,
                        value: "0",
                        model: {"icon": "hidden", "label": {"type": "text"}},
                        clickClose: true,
                        radio: true,
                        tree: {show: true, "strict": false, "clickCheck": true, "clickExpand": false},
                    });
                    if (res.code) {
                        return layui.popup.failure(res.msg);
                    }
                }
            });
        }


        function convertToTreeData(data, idField, parentIdField, nameField) {
            const treeData = [];
            const map = {};

            // 将数组中的每个元素映射到 map 对象中
            data.forEach(item => {
                map[item[idField]] = {...item, children: []};
            });

            // 遍历数组，构建树形结构
            data.forEach(item => {
                const parent = map[item[parentIdField]];
                if (parent) {
                    parent.children.push(map[item[idField]]);
                } else {
                    treeData.push(map[item[idField]]);
                }
            });

            // 对树形数据进行字段映射
            treeData.forEach(item => {
                item.value = item[idField];
                item.name = item[nameField];
                item.children.forEach(child => {
                    child.value = child[idField];
                    child.name = child[nameField];
                });
            });
            return treeData;
        }

        //监听事件
        form.on('submit(form-save)', function (data) {
            if (method === 'PUT') {
                data.field[PRIMARY_KEY] = layui.url().search[PRIMARY_KEY]
            }
            $.ajax({
                url: method === 'POST' ? INSERT_API : UPDATE_API,
                type: 'POST',
                headers: {Authorization: getUserInfo()["token"]},
                contentType: 'application/json',
                data: JSON.stringify(data.field),
                dataType: 'json',
                success: function (ret) {
                    if (ret && ret.code == 0) {
                        layer.msg(ret.msg, {
                            icon: 1,
                            time: 1000
                        }, function () {
                            parent.layer.close(parent.layer.getFrameIndex(window.name)); //关闭当前页
                            parent.refresh();
                        });
                        return false;
                    } else {
                        layer.msg(ret.msg, {
                            icon: 2,
                            time: 1000
                        });
                        return false;
                    }
                },
                error: function (ret) {
                    alert("出错" + ret.status + "：" + ret.responseText);
                }, //表示如果请求响应出现错误，会执行的回调函数
            });

            return false;
        });


        function getDept() {
            //访问接口
            $.ajax({
                url: DETAIL_API + '/' + getQueryString(PRIMARY_KEY), // 请求路径
                type: "GET", //请求方式
                headers: {Authorization: getUserInfo()["token"]},
                contentType: 'application/json',
                dataType: 'json',
                async: false,
                success: function (ret) {
                    if (ret.code !== 0) {
                        layer.msg(ret.msg, {
                            icon: 2,
                            time: 1000
                        }, function () {
                        });
                        return;
                    }

                    let post = ret.data;

                    $('#position_code').attr("value", post.position_code);
                    $('#pid').attr("value", post.department_id);
                    // $('#position_code').prop("disabled", "true");
                    $('#position_name').attr("value", post.position_name);
                    form.render();
                }, //响应成功后的回调函数
                error: function (ret) {
                    alert("出错" + ret.status + "：" + ret.responseText);
                }, //表示如果请求响应出现错误，会执行的回调函数
                contentType: 'application/x-www-form-urlencoded',
                dataType: "json" //设置接受到的响应数据的格式
            });

        }

        //业务场景
        if (getQueryString('operation') === 'edit') {
            getDept();
            getSuperiorDept();
        } else {
            getSuperiorDept();
        }
    })
</script>
</body>

</html>
